package com.msb.controller;

import com.msb.pojo.TblUserRecord;
import com.msb.response.Permission;
import com.msb.response.Permissions;
import com.msb.response.R;
import com.msb.response.UserInfo;
import com.msb.service.TblLoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 登录日志 前端控制器
 * </p>
 *
 * @author chshh
 * @since 2022-10-20
 */
@RestController
//@CrossOrigin(origins = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
public class TblLoginLogController {

    @Autowired
    private TblLoginLogService loginLogService;

    // 解决前端报错
    @RequestMapping("/auth/2step-code")
    public boolean step_code2(){
        System.out.println("此请求是前端框架带的默认请求，可以不做任何处理，也可以在前端将其删除");
        System.out.println("step_code2");
        return true;
    }

    //登录接口
    @PostMapping("/auth/login")
    public R login(@RequestParam("username") String username,
                   @RequestParam("password") String password,
                   HttpSession session){
        TblUserRecord tblUserRecord = loginLogService.login(username, password);
        tblUserRecord.setToken(tblUserRecord.getUserName());
        session.setAttribute("tblUserRecord",tblUserRecord);
        return new R(200,"success",tblUserRecord);
    }

    //用户信息接口
    @RequestMapping("/user/info")
    public R getInfo(HttpSession session) {
        // 获取用户信息
        TblUserRecord userRecord = (TblUserRecord) session.getAttribute("tblUserRecord");
        // 获取对应用户的功能模块
        String[] rolePrivileges = userRecord.getTblRole().getRolePrivileges().split("-");
        // 拼接需要返回的数据对象的格式
        Permissions permissions = new Permissions();
        List<Permission> permissionList = new ArrayList<>();
        for (String s : rolePrivileges) {
            permissionList.add(new Permission(s));
        }
        permissions.setPermissions(permissionList);
        UserInfo userInfo = new UserInfo(userRecord.getUserName(),"/avatar2.jpg", permissions);
        return new R(200,"success",userInfo);
    }

    //登出接口
    @RequestMapping("/auth/logout")
    public String LogOut(HttpSession session){
        System.out.println("logout");
        session.invalidate();//将Session设置为失效
        return "";
    }
}
